/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package dao.Cliente;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import pojo.Cliente;
import pojo.Endereco;
import util.SplitStringToNumberArray;

/**
 *
 * @author Andre Luiz
 */
public class ClienteDaoImpl implements ClienteDao {
    
    private final Collection<Cliente> clientes;
    
    public ClienteDaoImpl(){
        this.clientes = new ArrayList<> ();
    }
   
    @Override
    public boolean salvar(Cliente cliente){
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("smConfeccoesPU");
        EntityManager em = emf.createEntityManager ();
        try{
            em.getTransaction().begin();
            em.persist(cliente);
            em.getTransaction().commit();
            em.close();
            emf.close();
        }catch (RuntimeException e) {
            return false;
        }
        return true;
    }

    @Override
    public Collection<Cliente> listar(Cliente nomeObj) {
        return this.clientes;
    }
    
    @Override
    public ArrayList<Cliente> listarClientes(){
        return (ArrayList<Cliente>) clientes;
    }
    
    @Override
    public boolean remover(Cliente cliente) {
        return false;
    }

    @Override
    public Cliente buscar(Cliente cliente) {
        Cliente clienteTemp;
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("smConfeccoesPU");
        EntityManager em = emf.createEntityManager ();
        try{
            em.getTransaction().begin();
            clienteTemp = em.find(cliente.getClass(),cliente.getId());
            em.getTransaction().commit();
            em.close();
            emf.close();
        }catch (IllegalArgumentException e) {
            return null;
        }
        return clienteTemp;
    }
    
    @Override
    public Cliente buscarPorNome(Cliente nomeObj) {
        for(Cliente iteratorClientes : clientes){
            if(iteratorClientes.getNome().equals(nomeObj.getNome()))
                return iteratorClientes;
        }
        return nomeObj;
    }
    
    @Override
    public ArrayList<Cliente> buscarPorNome(String nome){
        ArrayList<Cliente> arrayClienteTemp = new ArrayList<Cliente>(); 
        for(Cliente clienteIterator : clientes){
            if(clienteIterator.getNome().contains(nome))
                arrayClienteTemp.add(clienteIterator);
        }
        return arrayClienteTemp;
    }
    
    @Override
    public boolean carregarDisco(){
        Cliente cliente;
        Endereco endereco;
        String pedidos;
        File arquivo = new File("registroClientes");
        if(!arquivo.exists()) return false;
        FileReader reader;
        BufferedReader leitor;
        try{
            reader = new FileReader(arquivo);
            leitor = new BufferedReader(reader);
            while(leitor.ready()){
                cliente = new Cliente();
                endereco = new Endereco();
                cliente.setId(Long.parseLong(leitor.readLine()));
                cliente.setNome(leitor.readLine());
                cliente.setCpf(Long.parseLong(leitor.readLine()));
                cliente.setTelefone(Long.parseLong(leitor.readLine()));
                endereco.setRua(leitor.readLine());
                endereco.setCep(Integer.parseInt(leitor.readLine()));
                endereco.setCidade(leitor.readLine());
                endereco.setComplemento(leitor.readLine());
                endereco.setNumero(Integer.parseInt(leitor.readLine()));
                endereco.setPais(leitor.readLine());
                cliente.setEndereco(endereco);
                pedidos = leitor.readLine();
                cliente.setPedidos(SplitStringToNumberArray.convertLong(pedidos));
                this.salvar(cliente);
                leitor.readLine();
            }
            reader.close();
            leitor.close();
        } catch (FileNotFoundException ex){
            Logger.getLogger(ClienteDaoImpl.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex){
            Logger.getLogger(ClienteDaoImpl.class.getName()).log(Level.SEVERE, null, ex);
        }
        return true;
    }
    @Override
    public boolean salvarDisco() {
        if(clientes == null) return false;
        try {
            FileWriter writer = new FileWriter ("registroClientes");
            PrintWriter saida = new PrintWriter (writer); 
            for (Cliente clienteIterator : clientes){
                saida.println(clienteIterator.getId());
                saida.println(clienteIterator.getNome());
                saida.println(clienteIterator.getCpf());
                saida.println(clienteIterator.getTelefone());
                saida.println(clienteIterator.getEndereco().getRua());
                saida.println(clienteIterator.getEndereco().getCep());
                saida.println(clienteIterator.getEndereco().getCidade());
                saida.println(clienteIterator.getEndereco().getComplemento());
                saida.println(clienteIterator.getEndereco().getNumero());
                saida.println(clienteIterator.getEndereco().getPais());
                if(clienteIterator.getPedidos().isEmpty()) saida.print("#");
                else {
                    for (long iteratorPedidos : clienteIterator.getPedidos()) {
                        saida.print(iteratorPedidos);
                        saida.print('#');
                    }
                }
                saida.println("\n");
            }
            writer.close();
            saida.close();
        }catch (IOException e) {
            System.out.println(e.toString());
            return false;
        }
        return true;
        
    }
}
